package com.huilian.iotbox.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.dao.RedisCacheDao;
import com.huilian.iotbox.admin.service.CacheService;
import com.huilian.iotbox.data.common.RedisHelper;
import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.vo.CacheVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Set;


@Service
public class CacheServiceImpl implements CacheService {
    @Resource
    private RedisHelper redisHelper;
    @Resource
    RedisCacheDao redisCacheDao;
    @Resource
    RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public ServerResponse findList(CacheVo cacheVo) {
        PageHelper.startPage(cacheVo.getPageNum(), cacheVo.getPageSize());
        List<CacheVo> list = redisCacheDao.findList(cacheVo);
        PageInfo pageResult = new PageInfo(list);
        return ServerResponse.createBySuccess(pageResult);
    }

    @Override
    public ServerResponse findListByKey(CacheVo cacheVo) {
        // 必须要以这个开头 防止搜到不该搜索的key
        Set<String> keys = redisHelper.keys(RedisKey.PROJECT_NAME + "*" + cacheVo.getKeyword() + "*");
        for (String key : keys) {
            cacheVo.getKeys().add(key);
        }
        PageInfo pageResult = new PageInfo(cacheVo.getKeys());
        return ServerResponse.createBySuccess(pageResult);
    }

    @Override
    public ServerResponse findCacheDetail(CacheVo cacheVo) {
        String res = null;
        try {
            Object serializable = redisCacheTemplate.opsForValue().get(cacheVo.getCacheKey());
            res = JSON.toJSONString(serializable);
        } catch (Exception e) {
            return ServerResponse.createBySuccess("取值失败!");
        }
        return ServerResponse.createBySuccess(res);
    }

    @Override
    public ServerResponse deleteCache(String key) {
        redisCacheTemplate.delete(key);
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse deleteKeyPrefix(Integer id) {
        CacheVo cacheVo = redisCacheDao.findOneById(id);
        if (StringUtils.isEmpty(cacheVo)){
            return ServerResponse.createByErrorMessage("该id不存在！");
        }
        redisCacheDao.delete(cacheVo.getId());
        Set<String> keys = redisHelper.keys(cacheVo.getKeyPrefix() + "*");
        for (String key : keys) {
            redisCacheTemplate.delete(key);
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public Integer insert(CacheVo cacheVo) {
        return redisCacheDao.insert(cacheVo);
    }
}
